// 我的地址   收货地址 与 发票地址
<template>
  <div class="myAddress" v-loading="loading">
    <ul class="title">
      <li
        v-for="(item,key) in title"
        :key="key"
        :class="key == index ? 'active' : '' "
        @click="changesjump($event,key)"
      >
        {{item.name}}
        <i v-show="item.num">({{item.num}})</i>
      </li>
    </ul>

    <div class="btn">
      <el-row>
        <el-col :span="2" :offset="22">
          <el-button @click="newAddress" size="mini">新增地址</el-button>
        </el-col>
      </el-row>
    </div>

    <el-dialog :title="titles" :visible.sync="centerDialogVisible" width="42%" center>
      <div>
        <el-form ref="form" :model="form" label-width="100px">
          <el-form-item :label="form.title" size="mini">
            <el-input v-model="form.name" placeholder="收件人姓名"></el-input>
          </el-form-item>

          <el-form-item label="所在地区：">
            <el-select @change="region1" v-model="form.region1.id" placeholder="请选择省份" size="mini">
              <el-option
                v-for="item in form.region1"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>

            <el-select @change="region2" v-model="form.region2.id" placeholder="请选择城市" size="mini">
              <el-option
                v-for="item in form.region2"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>

            <el-select @change="region3" v-model="form.region3.id" placeholder="请选择所在区" size="mini">
              <el-option
                v-for="item in form.region3"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="详细地址：">
            <el-input type="textarea" v-model="form.address" placeholder="详细地址"></el-input>
          </el-form-item>

          <el-form-item label="联系电话：" size="mini">
            <el-input v-model="form.tel" placeholder="手机号码/座机号"></el-input>
          </el-form-item>

          <el-form-item label="默认地址：" prop="is_default">
            <el-switch v-model="form.is_default"></el-switch>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="newAddressConfirmation" v-if="flag">确 定</el-button>
        <el-button type="warning" @click="editAddress" v-else>确 定</el-button>
      </span>
    </el-dialog>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column :label="peoples" width="180" prop="name">
        <template slot-scope="scope">
          <i
            class="el-icon-time"
            v-show="scope.row.is_default"
            title="默认地址"
            style="color:#b8defc"
          >默认</i>
          <span>{{scope.row.consignee}}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" width="180" prop="phone"></el-table-column>
      <el-table-column label="收货地址">
        <template slot-scope="scope">
          {{scope.row.province_name}}
          {{scope.row.city_name}}
          {{scope.row.district_name}}
          {{scope.row.address}}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <!-- <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button> -->
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row, scope.row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: "myAddress",

  data() {
    return {
      title: [
        {
          name: "收货地址",
          id: 0
        },
        {
          name: "发票地址",
          id: 1
        }
      ],
      type: 1,  // 收货地址 和 发票地址的接口区分
      flag: true,  //编辑按钮和新增按钮的区分
      loading: false,
      AddressCombination: [], // 地址组合放进这个里面      后期把这个数组给后台就好
      centerDialogVisible: false,
      titles: "新增收货人地址",
      peoples: "收货人",
      form: {
        title: "收货人：",
        name: "",
        region1: [],
        region2: [],
        region3: [],
        address: "",
        tel: "",
        is_default: false
      },
      index: 0,  // 菜单栏切换的效果的 index
      tableData: []
    }
  },

  methods: {
    // onSubmit() {

    //   console.log(this.form)
    //   console.log("submit!")
    // },
    // 新增地址的确认
    async newAddressConfirmation() {

      this.centerDialogVisible = false
      // this.conversion = true
      // console.log(this.AddressCombination)
      let [
        user_id, //用户ID
        consignee, //收货人
        province_id, //省份id
        province_name, //省份名称
        city_id, //城市id
        city_name, //城市名称
        district_id, //地区id
        district_name, //地区名称
        address, //详细地址
        phone, //联系电话
        type, //1：收货地址，2：发票地址
        is_default //默认地址 0：不默认，1：默认
      ] = [
          this.$store.state.UserInfor.user_id,
          this.form.name,
          this.AddressCombination["province"].id,
          this.AddressCombination["province"].name,
          this.AddressCombination["city"].id,
          this.AddressCombination["city"].name,
          this.AddressCombination["area"].id,
          this.AddressCombination["area"].name,
          this.form.address,
          this.form.tel,
          this.type,
          null
        ]

      if (this.form.is_default) {
        is_default = "1"
      } else {
        is_default = "0"
      }
      let obj = {
        user_id, //用户ID
        consignee, //收货人
        province_id, //省份id
        province_name, //省份名称
        city_id, //城市id
        city_name, //城市名称
        district_id, //地区id
        district_name, //地区名称
        address, //详细地址
        phone, //联系电话
        type, //1：收货地址，2：发票地址
        is_default //默认地址 0：不默认，1：默认
      }
      // console.log(obj)
      let arr = Object.values(obj)
      if (arr.includes("")) {
        this.$notify({
          title: "警告",
          message: "请填写完整的地址信息",
          type: "warning"
        })
        return
      }

      let addAddress = await this.$http({
        method: "post",
        url: "/api/home/index/saveaddress",
        data: {
          user_id, //用户ID
          consignee, //收货人
          province_id, //省份id
          province_name, //省份名称
          city_id, //城市id
          city_name, //城市名称
          district_id, //地区id
          district_name, //地区名称
          address, //详细地址
          phone, //联系电话
          type, //1：收货地址，2：发票地址
          is_default //默认地址 0：不默认，1：默认
        }
      })
      if (addAddress.data.State.Code == 200) {
        this.dialogFormVisible2 = false
        this.$notify({
          title: "成功",
          message: "成功增加地址...",
          type: "success"
        })
      }
      this.getReceivingAddressInfo()
    },
    // 编辑地址的确认
    async editAddress() {
      this.centerDialogVisible = false
      // this.conversion = true
      // console.log(this.AddressCombination)
      let [
        id,
        user_id, //用户ID
        consignee, //收货人
        province_id, //省份id
        province_name, //省份名称
        city_id, //城市id
        city_name, //城市名称
        district_id, //地区id
        district_name, //地区名称
        address, //详细地址
        phone, //联系电话
        type, //1：收货地址，2：发票地址
        is_default //默认地址 0：不默认，1：默认
      ] = [
          this.id,
          this.$store.state.UserInfor.user_id,
          this.form.name,
          this.AddressCombination["province"].id,
          this.AddressCombination["province"].name,
          this.AddressCombination["city"].id,
          this.AddressCombination["city"].name,
          this.AddressCombination["area"].id,
          this.AddressCombination["area"].name,
          this.form.address,
          this.form.tel,
          this.type,
          null
        ]

      if (this.form.is_default) {
        is_default = "1"
      } else {
        is_default = "0"
      }
      let obj = {
        id,
        user_id, //用户ID
        consignee, //收货人
        province_id, //省份id
        province_name, //省份名称
        city_id, //城市id
        city_name, //城市名称
        district_id, //地区id
        district_name, //地区名称
        address, //详细地址
        phone, //联系电话
        type, //1：收货地址，2：发票地址
        is_default //默认地址 0：不默认，1：默认
      }
      // console.log(obj)
      let arr = Object.values(obj)
      if (arr.includes("")) {
        this.$notify({
          title: "警告",
          message: "请填写完整的地址信息",
          type: "warning"
        })
        return
      }

      let addAddress = await this.$http({
        method: "post",
        url: "/api/home/index/editaddress",
        data: {
          id,
          user_id, //用户ID
          consignee, //收货人
          province_id, //省份id
          province_name, //省份名称
          city_id, //城市id
          city_name, //城市名称
          district_id, //地区id
          district_name, //地区名称
          address, //详细地址
          phone, //联系电话
          type, //1：收货地址，2：发票地址
          is_default //默认地址 0：不默认，1：默认
        }
      })
      if (addAddress.data.State.Code == 200) {
        this.dialogFormVisible2 = false
        this.$notify({
          title: "成功",
          message: "成功修改该地址...",
          type: "success"
        })
      }
      this.getReceivingAddressInfo()
    },
    // 获取收货地址数据
    async getReceivingAddressInfo() {
      this.loading = true
      let user_id = this.$store.state.UserInfor.user_id
      let type = this.type
      let res = await this.$http({
        method: 'post',
        url: '/api/home/index/getaddresslist',
        data: {
          user_id,
          type
        }
      })
      if (res.data.State.Code == 200) {
        this.tableData = res.data.data
        // console.log(res.data.data)
      }
      this.loading = false

    },
    // 通过id匹配名字
    SearchItem(pid, obj) {
      let mySearchItem = obj.find(obj => {
        return obj.id === pid
      })
      return mySearchItem
    },

    async region1() {
      let pid = this.form.region1.id
      let obj = this.form.region1
      this.SearchItem(pid, obj)

      this.AddressCombination["province"] = this.SearchItem(pid, obj)
      // console.log(this.AddressCombination)

      // console.log(pid)
      let Province = await this.$http({
        method: "post",
        url: "/api/home/index/linkagearea",
        data: {
          pid
        }
      })
      const myProvince = Province.data
      if (myProvince.State.Code == 200) {
        this.form.region2 = myProvince.data
      }
    },

    async region2() {
      let pid = this.form.region2.id
      let obj = this.form.region2
      this.SearchItem(pid, obj)

      this.AddressCombination["city"] = this.SearchItem(pid, obj)
      // console.log(this.AddressCombination)

      let Province = await this.$http({
        method: "post",
        url: "/api/home/index/linkagearea",
        data: {
          pid
        }
      })
      const myProvince = Province.data
      if (myProvince.State.Code == 200) {
        // console.log(myProvince.data)
        this.form.region3 = myProvince.data
      }
    },
    region3() {
      let pid = this.form.region3.id
      let obj = this.form.region3
      this.SearchItem(pid, obj)

      this.AddressCombination["area"] = this.SearchItem(pid, obj)
      // console.log(this.AddressCombination)
    },
    // 获取三级联动
    async getInfor() {
      let Province = await this.$http({
        method: "post",
        url: "/api/home/index/linkagearea",
        data: {}
      })
      const myProvince = Province.data
      if (myProvince.State.Code == 200) {
        // console.log(myProvince.data)
        this.form.region1 = myProvince.data
      }
    },



    changesjump(ev, key) {
      this.index = key
      if (this.index == 0) {
        
        this.titles = "新增收货人地址"
        this.peoples = "收货人"
        this.form.title = "收货人："
        this.type = 1
        console.log('点击了收货地址')
      } 
      else if (this.index == 1) {

        this.titles = "新增收票人地址"
        this.peoples = "收票人"
        this.form.title = "收票人："
        this.type = 2
        console.log('点击了发票地址')
      }
      this.getReceivingAddressInfo()
    },
    // 新增地址
    newAddress() {
      this.centerDialogVisible = true
      this.flag = true

      this.form.name = ""
      this.form.tel = ""
      this.form.address = ""
      this.form.is_default = "0"
    },
    // 编辑事件
    handleEdit(index, row) {
      this.flag = false
      // console.log(index, row)
      this.centerDialogVisible = true

      this.form.name = this.tableData[index].consignee
      this.form.tel = this.tableData[index].phone
      this.form.address = this.tableData[index].address
      this.form.DefaultAddress = this.tableData[index].is_default
      this.id = this.tableData[index].id
    },
    // 删除事件
    async handleDelete(index, row, id) {
      let user_id = this.$store.state.UserInfor.user_id
      let res = await this.$http({
        method: 'post',
        url: '/api/home/index/deladdress',
        data: {
          user_id,
          id
        }
      })
      if (res.data.State.Code == 200) {
        // console.log(res)
        this.tableData.splice(index, 1)
      }
    }
  },

  mounted() {
    this.getInfor()
    this.getReceivingAddressInfo()
  }
}
</script>

<style lang="scss" scoped>
.myAddress {
  width: 970px;
  background: #fff;
  padding: 15px;
  box-sizing: border-box;
  // padding-bottom: 800px;
  margin-bottom: 30px;
  .title {
    display: flex;
    flex-direction: row;
    border-bottom: 1px solid #f7f7f7;
    margin-bottom: 20px;
    li {
      line-height: 56px;
      font-size: 16px;
      text-align: center;
      padding: 5px 10px;
      letter-spacing: 1.5px;
      margin: 0 15px;
      cursor: pointer;
      i {
        color: #ff9000;
      }
    }
    .active {
      color: #ff9000;
      line-height: 56px;
      font-weight: bold;
      border-bottom: #ff9000 solid 2px;
    }
  }
  .btn {
    margin-bottom: 15px;
  }
}
</style>
